package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.constant.BsQiyeConstants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.BsJingqu;
import com.ruoyi.system.domain.BsQiye;
import com.ruoyi.system.domain.BsZhusu;
import com.ruoyi.system.domain.dto.BsCountNumDTO;
import com.ruoyi.system.domain.ro.BsQiyeEnterRo;
import com.ruoyi.system.domain.ro.BsQiyeRo;
import com.ruoyi.system.mapper.BsQiyeMapper;
import com.ruoyi.system.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 涉旅企业管理Service业务层处理
 *
 * @author ruoyi
 * @date 2023-10-29
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class BsQiyeServiceImpl implements IBsQiyeService {

    private final static String SYNC_ZHU_SU = "jiudian||minsu";
    private final BsQiyeMapper baseMapper;
    private final BsZhusuService zhusuService;
    private final BsJingquService bsJingquService;
    private final IBsQiyeBusinessDataService iBsQiyeBusinessDataService;
    private final IBsQiyeMerchandiseService iBsQiyeMerchandiseService;

    /**
     * 商户端-店铺入驻
     */
    @Override
    public Boolean insertByBo(BsQiyeEnterRo bo) {
        BsQiye add = BeanUtil.toBean(bo, BsQiye.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 批量删除涉旅企业管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 修改涉旅企业管理
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(BsQiyeRo ro) {
        BsQiye update = BeanUtil.toBean(ro, BsQiye.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 修改涉旅企业管理
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateStatus(BsQiyeRo ro) {
        update(ro);
        BsQiye bsQiye = baseMapper.selectById(ro.getId());
        //对接住宿管理
        if (BsQiyeConstants.MERCHANT_TYPE.JIUDIAN.equals(bsQiye.getType())
                || BsQiyeConstants.MERCHANT_TYPE.MINSU.equals(bsQiye.getType())) {
            log.info("酒店、民宿同步住宿:{}", JSON.toJSONString(bsQiye));
            zhusuService.updateStatusByQiyeId(bsQiye.getId(), ro.getStatus());
        }
        return true;
    }

    /**
     * 审批涉旅企业管理
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean auditByBo(BsQiyeRo ro) {
        BsQiye update = BeanUtil.toBean(ro, BsQiye.class);
        validEntityBeforeSave(update);
        baseMapper.updateById(update);
        BsQiye bsQiye = baseMapper.selectById(ro.getId());
        //对接住宿管理
        if (ro.getAuditStatus().equals(BsQiyeConstants.AUDIT_STATUS.AUDIT_ALLOW)) {
//            if (BsQiyeConstants.MERCHANT_TYPE.JIUDIAN.equals(bsQiye.getType())
//                    || BsQiyeConstants.MERCHANT_TYPE.MINSU.equals(bsQiye.getType())) {
//                log.info("酒店、民宿同步住宿:{}", JSON.toJSONString(bsQiye));
//                zhusuService.saveEntity(BsZhusu.builder()
//                        .qiyeId(bsQiye.getId())
//                        .name(bsQiye.getName())
//                        .address(bsQiye.getAddress())
//                        .phone(bsQiye.getBusinessPhone())
//                        .img(bsQiye.getDoorImg())
//                        .type(bsQiye.getType())
//                        .status(bsQiye.getStatus())
//                        .jingquId(bsQiye.getJingquId())
//                        .build());
//            }
            iBsQiyeBusinessDataService.initTodayUnReportData(bsQiye.getId(), DateUtil.today());
        }
        return true;
    }

    /**
     * 查询涉旅企业管理列表
     */
    @Override
    public List<BsQiye> queryList(BsQiyeRo ro, boolean hasCulturalAndCreative) {
        LambdaQueryWrapper<BsQiye> lqw = buildQueryWrapper(ro, hasCulturalAndCreative);
        List<BsQiye> bsQiyes = baseMapper.selectList(lqw);
        List<Long> jingquIds = bsQiyes.stream().map(BsQiye::getJingquId).filter(ObjectUtil::isNotNull).collect(Collectors.toList());
        if (!jingquIds.isEmpty()) {
            List<BsJingqu> list = bsJingquService.list(new QueryWrapper<BsJingqu>().lambda().in(BsJingqu::getJingquId, jingquIds));
            Map<Long, String> collect = list.stream().collect(Collectors.toMap(BsJingqu::getJingquId, BsJingqu::getJingquName));
            bsQiyes.forEach(f -> f.setJingquName(collect.get(f.getJingquId())));
        }
        if (hasCulturalAndCreative && !bsQiyes.isEmpty()) {
            List<Long> bsQiyeIds = bsQiyes.stream().map(BsQiye::getId).filter(ObjectUtil::isNotNull).collect(Collectors.toList());
            //统计文创数据商品 种类统计
            List<BsCountNumDTO> countList = iBsQiyeMerchandiseService.countMerchandise(bsQiyeIds);
            Map<Long, Integer> collect = countList.stream().collect(Collectors.toMap(BsCountNumDTO::getAimId, BsCountNumDTO::getCountNum));
            bsQiyes.forEach(f -> {
                Long qiYeId = f.getId();
                f.setMerchandiseNum(0);
                if (collect.containsKey(qiYeId)) {
                    f.setMerchandiseNum(collect.get(qiYeId));
                }
            });

        }
        return bsQiyes;
    }

    /**
     * 查询涉旅企业管理
     */
    @Override
    public BsQiye queryById(Long id) {
        BsQiye bsQiye = baseMapper.selectById(id);
        BsJingqu jingqu = bsJingquService.getById(bsQiye.getJingquId());
        if (jingqu != null) {
            bsQiye.setJingquName(jingqu.getJingquName());
        }
        return bsQiye;
    }

    private LambdaQueryWrapper<BsQiye> buildQueryWrapper(BsQiyeRo ro, boolean hasCulturalAndCreative) {
        Map<String, Object> params = ro.getParams();
        LambdaQueryWrapper<BsQiye> lqw = Wrappers.lambdaQuery();
        lqw.eq(ro.getId() != null, BsQiye::getId, ro.getId());
        lqw.eq(ro.getJingquId() != null, BsQiye::getJingquId, ro.getJingquId());
        lqw.like(StringUtils.isNotBlank(ro.getName()), BsQiye::getName, ro.getName());
        lqw.eq(StringUtils.isNotBlank(ro.getType()), BsQiye::getType, ro.getType());
        lqw.like(StringUtils.isNotBlank(ro.getAddress()), BsQiye::getAddress, ro.getAddress());
        lqw.eq(StringUtils.isNotBlank(ro.getBusinessPhone()), BsQiye::getBusinessPhone, ro.getBusinessPhone());
        lqw.like(StringUtils.isNotBlank(ro.getApplyName()), BsQiye::getApplyName, ro.getApplyName());
        lqw.like(StringUtils.isNotBlank(ro.getApplyPhone()), BsQiye::getApplyPhone, ro.getApplyPhone());
        lqw.eq(StringUtils.isNotBlank(ro.getStatus()), BsQiye::getStatus, ro.getStatus());
        lqw.eq(StringUtils.isNotBlank(ro.getAuditBy()), BsQiye::getAuditBy, ro.getAuditBy());
        lqw.eq(StringUtils.isNotBlank(ro.getAuditStatus()), BsQiye::getAuditStatus, ro.getAuditStatus());
        lqw.between(params.get("beginAuditTime") != null && StringUtils.isNotBlank(params.get("beginAuditTime").toString()) && params.get("endAuditTime") != null && StringUtils.isNotBlank(params.get("beginAuditTime").toString()),
                BsQiye::getAuditTime, params.get("beginAuditTime"), params.get("endAuditTime"));
        lqw.between(params.get("beginCreateTime") != null && StringUtils.isNotBlank(params.get("beginCreateTime").toString()) && params.get("endCreateTime") != null && StringUtils.isNotBlank(params.get("endCreateTime").toString()),
                BsQiye::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
        lqw.between(params.get("beginUpdateTime") != null && StringUtils.isNotBlank(params.get("beginUpdateTime").toString()) && params.get("endUpdateTime") != null && StringUtils.isNotBlank(params.get("endUpdateTime").toString()),
                BsQiye::getUpdateTime, params.get("beginUpdateTime"), params.get("endUpdateTime"));
        lqw.eq(StringUtils.isNotBlank(ro.getCreateBy()), BsQiye::getCreateBy, ro.getCreateBy());
        lqw.eq(StringUtils.isNotBlank(ro.getUpdateBy()), BsQiye::getUpdateBy, ro.getUpdateBy());
        lqw.eq(ro.getCreateById() != null, BsQiye::getCreateById, ro.getCreateById());
        lqw.notIn(hasCulturalAndCreative, BsQiye::getType, Arrays.asList(BsQiyeConstants.MERCHANT_TYPE.JIUDIAN, BsQiyeConstants.MERCHANT_TYPE.MINSU));
        lqw.orderByDesc(BsQiye::getCreateTime);
        return lqw;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BsQiye entity) {
        //TODO 做一些数据校验,如唯一约束
    }


}
